<template>
	<view class="edit-address-wrapper">
		<!--input列表 -->
		<view class="input-box" v-if="!isMap">
			<view class="section">
				<text>{{i18n.recipient}}</text>
				<input :placeholder="i18n.recipientName" type="text" maxlength="15" :value="receiver"
					@input="onReceiverInput"></input>
			</view>
			<view class="section">
				<text>{{i18n.mobilePhone}}</text>
				<input :placeholder="i18n.mobileNumberLength" type="number" maxlength="11" :value="mobile"
					@input="onMobileInput"></input>
			</view>
			<view class="section" @tap="translate" v-if="areaArray.length">
				<text>{{i18n.area}}</text>
				<view class="pca">{{province}} {{city}} {{area}}</view>
				<template v-if="showPicker">
					<view class="animation-element-wrapper" :animation="animation"
						:style="'visibility:' + (show ? 'visible':'hidden')" @tap.stop="hiddenFloatView">
						<view class="animation-element" @tap.stop="nono">
							<text class="right-bt" @tap.stop="hiddenFloatView">{{i18n.confirm}}</text>
							<view class="line"></view>
							<picker-view indicator-style="height: 50rpx;" :value="value" @change="bindChange"
								@tap.stop="nono">
								<!--省-->
								<picker-view-column>
									<view v-for="(item, index) in provArray" :key="index">{{item.areaName}}</view>
								</picker-view-column>
								<!--地级市-->
								<picker-view-column>
									<view v-for="(item, index) in cityArray" :key="index">{{item.areaName}}</view>
								</picker-view-column>
								<!--区县-->
								<picker-view-column>
									<view v-for="(item, index) in areaArray" :key="index">{{item.areaName}}</view>
								</picker-view-column>
							</picker-view>
						</view>
					</view>

				</template>
				<view class="arrow">
					<image src="/static/images/icon/more.png"></image>
				</view>
			</view>
			<view class="section">
				<text>{{i18n.detailedAddress}}</text>
				<input class="addr" :placeholder="i18n.addressTips" type="text" :value="addr" @input="onAddrInput"
					maxlength="50"></input>
				<view class="arrow add-icon" @tap="selMap">
					<image src="/static/images/icon/submit-address.png"></image>
				</view>
			</view>
		</view>
		<!-- end input列表 -->
		<!-- 功能按钮 -->
		<view class="btn-box" v-if="!isMap">
			<view class="keep btn" @tap="onSaveAddr">
				<text>{{i18n.saveAddress}}</text>
			</view>

			<view class="clear btn" @tap="onDeleteAddr" v-if="addrId!=0">
				<text>{{i18n.deleteAddress}}</text>
			</view>
		</view>
		<!-- end 功能按钮 -->

		<!-- 腾讯地图组件 -->
		<view class="map" v-if="isMap">
			<view class="goOut" @click="isMap=false">返回</view>
			<iframe id="mapPage" width="100%" height="100%" frameborder=0
				:src="`https://apis.map.qq.com/tools/locpicker?search=1&type=1&policy=1&key=${key}&referer=myapp`">
			</iframe>
			<!-- end 腾讯地图组件 -->
		</view>
	</view>
</template>

<script>
	var http = require("@/utils/http.js");
	var util = require("@/utils/util.js");
	var index = [18, 0, 0];
	var t = 0;
	var show = false;
	var moveY = 200;



	export default {
		data() {
			return {
				value: [0, 0, 0],
				provArray: [],
				cityArray: [],
				areaArray: [],
				province: "",
				city: "",
				area: "",
				provinceId: 0,
				cityId: 0,
				areaId: 0,
				receiver: "",
				mobile: "",
				addr: "",
				addrId: 0,
				animation: "",
				show: "",
				region: "",
				lat: '',
				lng: '',
				showPicker: false,
				key: 'L4DBZ-VSSKJ-GCDFX-KGBVR-KHZ2J-RNF2Q',
				isMap: false,
				isPosition: false
			};
		},

		components: {},
		props: {},
		computed: {
			i18n() {
				return this.$t('index')
			}
		},

		onLoad: function(options) {
			this.initCityData(this.provinceId, this.cityId, this.areaId);
			if (options.addrId) {
				uni.showLoading();
				var params = {
					url: "/p/address/addrInfo/" + options.addrId,
					method: "GET",
					data: {},
					callBack: res => {

						this.setData({
							provinceId: res.provinceId,
							cityId: res.cityId,
							areaId: res.areaId,
							receiver: res.receiver,
							mobile: res.mobile,
							addr: res.addr,
							addrId: options.addrId,
							lat: res.lat,
							lng: res.lng
						});

						this.initCityData(res.provinceId, res.cityId, res.areaId);
						uni.hideLoading()
					}
				};
				http.request(params);
			} else {
				this.initCityData(this.provinceId, this.cityId, this.areaId);
			}
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {
			// 加载导航标题
			uni.setNavigationBarTitle({
				title: this.i18n.editShippingAddress
			});
		},
		onHide: function() {
			this.showPicker = false
		},
		onReady: function() {
			this.animation = wx.createAnimation({
				transformOrigin: "50% 50%",
				duration: 0,
				timingFunction: "ease",
				delay: 0
			});
			this.animation.translateY(200 + 'vh').step();
			this.setData({
				animation: this.animation.export(),
				show: show
			});
		},
		methods: {

			//根据地图修改省份ID
			setProvinceId(province) {
				for (let i = 0; i < this.provArray.length; i++) {
					if (this.provArray[i].areaName === province) {
						let value = this.value
						value[0] = i
						this.setData({
							provinceId: this.provArray[i].areaId,
							value: value
						});
						this.getCityArray(this.provArray[i].areaId);
					}
				}
			},
			//根据地图修改市ID
			setCityId(city) {

				for (let i = 0; i < city.length; i++) {
					if (city[i].areaName === this.city) {

						let value = this.value
						value[1] = i
						this.setData({
							cityId: city[i].areaId,
							value: value
						});
						this.getAreaArray(this.cityId)
					}
				}
			},
			//根据地图修改区ID
			setAreaId(area) {
				for (let i = 0; i < area.length; i++) {
					if (area[i].areaName === this.area) {
						let value = this.value
						value[2] = i
						this.setData({
							areaId: area[i].areaId,
							value: [value[0], value[1], value[2]],
							isPosition: false
						});
						return uni.hideLoading();
					}
				}
			},

			/**
			 * 腾讯地图以及微信小程序详细地址请求
			 */
			selMap() {
				// #ifdef H5
				this.isMap = true
				let that = this
				window.addEventListener('message', function(event) {
					// 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
					var loc = event.data
					if (loc && loc.module ===
						'locationPicker') { // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
						that.addr = loc.poiaddress
						that.lat = loc.latlng.lat
						that.lng = loc.latlng.lng
						that.isMap = false
					}
				}, false)
				// #endif

				// #ifdef MP-WEIXIN
				let that = this
				uni.chooseLocation({
					success: function(res) {
						that.setMapData(res);
					},
					fail: function(failMsg) {
						// #ifdef MP-WEIXIN
						uni.getSetting({
							success(res) {
								if (!res.authSetting['scope.userLocation']) {
									console.log("f1");
									uni.authorize({
										scope: 'scope.userLocation',
										success() {
											uni.chooseLocation({
												success: function(res) {
													that.setMapData(res);
												}
											});
											console.log('success2');
											that.isPosition = true
											that.setProvinceId(that.province)
										},
										fail() {
											uni.showToast({
												title: that.i18n.authorityTips,
												icon: 'none'
											});
										}
									});
								}
							}
						});
						// #endif
					}
				});
				// #endif
				// #ifdef APP-PLUS
				let that = this

				uni.chooseLocation({
					success: function(res1) {
						// that.setMapData(res);
						// console.log(res1)
						uni.getLocation({
							type: 'wgs84',
							geocode: true,
							success: function(res) {
								console.log(res)
								that.setData({
									latitude: res.latitude,
									longitude: res.longitude,
									province: res.address.province,
									city: res.address.city,
									area: res.address.district,
									mapAddress: res1.address,
									mapAddrName: res1.name,
									addr: res1.address,
									isPosition: true
								});
								that.setProvinceId(that.province)
							}
						});
					}
				});
				// #endif
			},

			initCityData: function(provinceId, cityId, areaId) {
				var ths = this;
				uni.showLoading();
				var params = {
					url: "/p/area/listByPid",
					method: "GET",
					data: {
						pid: 0
					},
					callBack: function(res) {
						ths.setData({
							provArray: res
						});
						if (provinceId) {
							for (var index in res) {
								if (res[index].areaId == provinceId) {
									ths.setData({
										value: [Number(index), ths.value[1], ths.value[2]],
										province: res[index].areaName
									});
								}
							}
						}
						ths.getCityArray(provinceId ? provinceId : res[0].areaId, cityId, areaId);
						uni.hideLoading()

					}
				};
				http.request(params);
			},

			//滑动事件
			bindChange: function(e) {
				var ths = this;
				var val = e.detail.value; //判断滑动的是第几个column
				console.log(ths.addr)

				//若省份column做了滑动则定位到地级市和区县第一位
				if (index[0] != val[0]) {
					val[1] = 0;
					val[2] = 0; //更新数据
					console.log('省份改变', this.provArray[val[0]].areaId)
					ths.getCityArray(this.provArray[val[0]].areaId); //获取地级市数据
				} else {
					//若省份column未做滑动，地级市做了滑动则定位区县第一位
					if (index[1] != val[1]) {
						val[2] = 0; //更新数据

						ths.getAreaArray(this.cityArray[val[1]].areaId); //获取区县数据
					} else {}
				}

				index = val;
				this.setData({
					value: [val[0], val[1], val[2]]
				});
				ths.setData({
					province: ths.provArray[ths.value[0]].areaName,
					city: ths.cityArray[ths.value[1]].areaName,
					area: ths.areaArray[ths.value[2]].areaName,
					provinceId: ths.provArray[ths.value[0]].areaId,
					cityId: ths.cityArray[ths.value[1]].areaId,
					areaId: ths.areaArray[ths.value[2]].areaId
				});
			},

			//移动按钮点击事件
			translate: function(e) {
				if (t == 0) {
					moveY = 0;
					show = false;
					t = 1;
				} else {
					moveY = 200;
					show = true;
					t = 0;
				}

				this.setData({
					show: true,
					showPicker: true
				}); // this.animation.translate(arr[0], arr[1]).step();

				this.animationEvents(this, moveY, show);
			},

			//隐藏弹窗浮层
			hiddenFloatView(e) {
				//console.log(e);
				moveY = 200;
				show = true;
				t = 0;
				this.initCityData(this.provinceId, this.cityId, this.areaId);
				this.animationEvents(this, moveY, show);
			},

			//动画事件
			animationEvents: function(that, moveY, show) {
				//console.log("moveY:" + moveY + "\nshow:" + show);
				that.animation = wx.createAnimation({
					transformOrigin: "50% 50%",
					duration: 400,
					timingFunction: "ease",
					delay: 0
				});
				that.animation.translateY(moveY + 'vh').step();
				that.setData({
					animation: that.animation.export()
				});
			},

			/**
			 * 根据省份ID获取 城市数据
			 */
			getCityArray: function(provinceId, cityId, areaId) {

				uni.showLoading();
				var ths = this;
				var params = {
					url: "/p/area/listByPid",
					method: "GET",
					data: {
						pid: provinceId
					},
					callBack: function(res) {
						uni.hideLoading()
						ths.setData({
							cityArray: res
						});
						if (ths.isPosition) {
							ths.setCityId(res)
							return;
						}
						if (cityId) {
							for (var index in res) {
								if (res[index].areaId == cityId) {
									ths.setData({
										value: [ths.value[0], Number(index), Number(ths.value[2])],
										city: res[index].areaName
									});
								}
							}
						}

						ths.getAreaArray(cityId ? cityId : res[0].areaId, areaId);
					}
				};
				http.request(params);
			},

			/**
			 * 根据城市ID获取 区数据
			 */
			getAreaArray: function(cityId, areaId) {
				var ths = this;
				var params = {
					url: "/p/area/listByPid",
					method: "GET",
					data: {
						pid: cityId
					},
					callBack: function(res) {
						uni.hideLoading()
						ths.setData({
							areaArray: res
						});
						if (ths.isPosition) {
							ths.setAreaId(res)
							return;
						}
						if (areaId) {
							for (var _index in res) {
								if (res[_index].areaId == areaId) {
									ths.setData({
										value: [ths.value[0], ths.value[1], Number(_index)],
										area: res[_index].areaName
									});
								}
							}

							index = ths.value;
							ths.setData({
								province: ths.province,
								city: ths.city,
								area: ths.area,
								provinceId: ths.provinceId,
								cityId: ths.cityId,
								areaId: ths.areaId
							});
						} else {
							ths.setData({
								province: ths.provArray[ths.value[0]].areaName,
								city: ths.cityArray[ths.value[1]].areaName,
								area: ths.areaArray[ths.value[2]].areaName,
								provinceId: ths.provArray[ths.value[0]].areaId,
								cityId: ths.cityArray[ths.value[1]].areaId,
								areaId: ths.areaArray[ths.value[2]].areaId
							});
						}

					}
				};
				http.request(params);
			},
			bindRegionChange: function(e) {
				//console.log('picker发送选择改变，携带值为', e.detail.value)
				this.setData({
					region: e.detail.value
				});
			},

			/**
			 * 保存地址
			 */
			onSaveAddr: function() {
				var ths = this;
				var receiver = ths.receiver;
				var mobile = ths.mobile;
				var addr = ths.addr;
				var lat = ths.lat
				var lng = ths.lng
				console.log('提交的经纬度：', lng, ',', lat)
				if (!receiver) {
					uni.showToast({
						title: ths.i18n.consigneeTips,
						icon: "none"
					});
					return;
				}
				if (!mobile) {
					uni.showToast({
						title: ths.i18n.enterMobileNumber,
						icon: "none"
					});
					return;
				}
				if (!util.checkPhoneNumber(mobile)) {
					uni.showToast({
						title: ths.i18n.enterCorrectPhone,
						icon: "none"
					});
					return;
				}
				if (!addr || addr.length < 5) {
					uni.showToast({
						title: ths.i18n.selectDetailedAddress,
						icon: "none"
					});
					return;
				}
				uni.showLoading();
				var url = "/p/address/addAddr";
				var method = "POST";

				if (ths.addrId != 0) {
					url = "/p/address/updateAddr";
					method = "PUT";
				} //添加或修改地址

				var params = {
					url: url,
					method: method,
					data: {
						receiver: ths.receiver,
						mobile: ths.mobile,
						addr: ths.addr,
						province: ths.province,
						provinceId: ths.provinceId,
						city: ths.city,
						cityId: ths.cityId,
						areaId: ths.areaId,
						area: ths.area,
						userType: 0,
						addrId: ths.addrId,
						lat: ths.lat, // 经度
						lng: ths.lng, // 纬度
					},
					callBack: function(res) {
						uni.hideLoading()
						uni.navigateBack({
							delta: 1
						});
					}
				};
				http.request(params);
			},
			onReceiverInput: function(e) {
				this.setData({
					receiver: e.detail.value
				});
			},
			onMobileInput: function(e) {
				this.setData({
					mobile: e.detail.value
				});
			},
			onAddrInput: function(e) {
				this.setData({
					addr: e.detail.value
				});
			},
			//删除配送地址
			onDeleteAddr: function(e) {
				var ths = this;
				uni.showModal({
					title: '',
					content: ths.i18n.deleteAddressTips,
					cancelText: ths.i18n.cancel,
					confirmText: ths.i18n.confirm,
					confirmColor: "#eb2444",

					success(res) {
						if (res.confirm) {
							var addrId = ths.addrId;
							uni.showLoading();
							var params = {
								url: "/p/address/deleteAddr/" + addrId,
								method: "DELETE",
								data: {},
								callBack: function(res) {
									uni.hideLoading()
									uni.navigateBack({
										delta: 1
									});
								}
							};
							http.request(params);
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}

				});
			},

			setMapData(res) {
				this.lat = res.latitude; // 纬度
				this.lng = res.longitude; // 经度
				this.addr = res.address; // 详细地址
				this.name = res.name; // 详细地址

				console.log('腾讯/高德地图经纬度：', this.lng, '，', this.lat)

				this.qqMapTransBMap(this.lng, this.lat)
			}

		},

		// 将腾讯/高德地图经纬度转换为百度地图经纬度
		qqMapTransBMap: function(lng, lat) {
			let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
			let x = lng;
			let y = lat;
			let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
			let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
			let lngs = z * Math.cos(theta) + 0.0065;
			let lats = z * Math.sin(theta) + 0.006;

			this.lng = lngs
			this.lat = lats

			console.log('百度地图经纬度：', this.lng, '，', this.lat)
			return {
				lng: lngs,
				lat: lats
			}
		},


		// 空方法
		nono() {

		}
	}
</script>
<style lang="scss">
	page {
		background: #fff;
	}

	.edit-address-wrapper {
		/* input列表 */
		height: 100vh;

		.input-box {
			margin-bottom: 100rpx;
			background: #fff;
			padding: 0 20rpx;

			.section {
				display: flex;
				align-items: center;
				width: 100%;
				font-size: 30rpx;
				padding: 30rpx 0;
				line-height: 48rpx;
				height: 100%;
				box-sizing: border-box;
				border-bottom: 2rpx solid #e5e5e5;

				text {
					width: 20%;
				}

				input {
					width: 70%;
					padding: 0 20rpx;
				}

				picker {
					width: 70%;
					padding: 0 30rpx;
				}

				.pca {
					width: 70%;
					padding: 0 20rpx;
				}

				.arrow {
					width: 28rpx;
					height: 28rpx;

					image {
						width: 100%;
						height: 100%;
						vertical-align: top;
					}
				}

				.add-icon {
					width: 40rpx;
					height: 40rpx;
					padding-right: 30rpx;
				}

				.addr {
					width: 460rpx;
				}
			}
		}

		/* end input列表 */

		/* 功能按钮 */

		.btn-box {
			padding: 5px 0;
			width: 100%;
			text-align: center;
			margin: auto;

			text {
				font-size: 30rpx;
			}

			.keep {
				color: #fff;
				background-color: #e43130;
			}
		}

		.btn-box .clear.btn,
		.keep.btn {
			width: 60%;
			height: 80rpx;
			line-height: 80rpx;
			margin: auto;
			text-align: center;
			border: 1rpx solid #e43130;
			border-radius: 50rpx;
			box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05), 0 1px 0 rgba(255, 255, 255, 0.3);
		}

		.btn-box .clear.btn {
			margin-top: 40rpx;
			color: #e43130;
		}


		picker-view {
			background-color: white;
			padding: 0;
			width: 100%;
			height: 380rpx;
			bottom: 0;
			position: fixed;
		}

		picker-view-column view {
			vertical-align: middle;
			font-size: 30rpx;
			line-height: 30rpx;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.animation-element-wrapper {
			display: flex;
			position: fixed;
			left: 0;
			top: 0;
			height: 100%;
			width: 100%;
			background-color: rgba(0, 0, 0, 0.6);
			z-index: 999;
		}

		.animation-element {
			display: flex;
			position: fixed;
			width: 100%;
			height: 530rpx;
			bottom: 0;
			background-color: rgba(255, 255, 255, 1);

			.right-bt {
				right: 35rpx;
				top: 20rpx;
				position: absolute;
				width: 80rpx !important;
			}

			.line {
				display: block;
				position: fixed;
				height: 2rpx;
				width: 100%;
				margin-top: 89rpx;
				background-color: #eee;
			}
		}

		picker-view text {
			color: #999;
			display: inline-flex;
			position: fixed;
			margin-top: 20rpx;
			height: 50rpx;
			text-align: center;
			line-height: 50rpx;
			font-size: 34rpx;
			font-family: Arial, Helvetica, sans-serif;
		}

		.map {
			height: 100%;

			.goOut {
				text-align: center;
			}
		}
	}
</style>
